/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.policy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.collections.CollectionUtils;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.modules.policy.dto.CashAcceptDTO;
import org.springblade.modules.policy.dto.EhbCashAcceptDTO;
import org.springblade.modules.policy.entity.MatMatter;
import org.springblade.modules.policy.entity.PolicyDraw;
import org.springblade.modules.policy.entity.PolicyDrawProcess;
import org.springblade.modules.policy.mapper.MatMatterMapper;
import org.springblade.modules.policy.service.IMatMatterService;
import org.springblade.modules.policy.service.IPolicyDrawProcessService;
import org.springblade.modules.policy.service.IPolicyDrawService;
import org.springblade.modules.policy.vo.MatMatterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务实现类
 *
 * @author Blade
 * @since 2022-07-29
 */
@Service
public class MatMatterServiceImpl extends BaseServiceImpl<MatMatterMapper, MatMatter> implements IMatMatterService {
	@Autowired
	protected IPolicyDrawService policyDrawService;
	@Autowired
	private IPolicyDrawProcessService policyDrawProcessService;

	@Override
	public IPage<MatMatterVO> selectMatMatterPage(IPage<MatMatterVO> page, MatMatterVO matMatter) {
		return page.setRecords(baseMapper.selectMatMatterPage(page, matMatter));
	}

	@Override
	public Map<String, Integer> handleStatistics(List<Date> createTime, Map<String, Object> matMatter) {
		QueryWrapper<MatMatter> queryWrapper = Condition.getQueryWrapper(matMatter, MatMatter.class);
		queryWrapper.select("id,handle_num,matter_id,matter_name,do_state_name handing_dept, applied_cash_amount,enterprise_code,create_time, finish_time, handle_status");
		if (CollectionUtils.isNotEmpty(createTime)) {
			queryWrapper.between("create_time", createTime.get(0), createTime.get(1));
		}
		List<MatMatter> list = list(queryWrapper);
		Map<String, Integer> map = new HashMap<>();
		map.put("handleCount", 0);
		map.put("entDistinctCount", 0);
		map.put("entCount", list.size());
		List<String> handleStr = new ArrayList<>();
		List<String> entDistinctStr = new ArrayList<>();
		list.forEach((MatMatter mat) -> {
			if (!handleStr.contains(mat.getHandleNum())) {
				map.put("handleCount", map.get("handleCount") + 1);
				handleStr.add(mat.getHandleNum());
			}
			if (!entDistinctStr.contains(mat.getEnterpriseCode())) {
				map.put("entDistinctCount", map.get("entDistinctCount") + 1);
				entDistinctStr.add(mat.getEnterpriseCode());
			}
		});
		return map;
	}

	@Override
	public IPage<MatMatter> selectMatMatterPageByHandelNum(List<Date> createTime, Map<String, Object> matMatter, Query query) {
		QueryWrapper<MatMatter> queryWrapper = Condition.getQueryWrapper(matMatter, MatMatter.class);
		queryWrapper.select("any_value(id) as id, handle_num, any_value(matter_id) as matter_id,any_value(do_state_name) as do_state_name, any_value(matter_name) as matter_name, any_value(handing_dept) as handing_dept, SUM(applied_cash_amount) AS applied_cash_amount, any_value(create_time) as  create_time, any_value(finish_time) as finish_time, any_value(handle_status) as handle_status");
		if (CollectionUtils.isNotEmpty(createTime)) {
			queryWrapper.between("create_time", createTime.get(0), createTime.get(1));
		}
		queryWrapper.groupBy("handle_num");
		IPage<MatMatter> pages = page(Condition.getPage(query), queryWrapper);
		return pages;
	}

	@Override
	public Boolean cashAccpet(CashAcceptDTO cashAcceptDTO) {
		PolicyDraw policyDraw = policyDrawService.getById(Long.valueOf(cashAcceptDTO.getItemCode()));
		MatMatter matMatter = new MatMatter();
		matMatter.setHandleNum(cashAcceptDTO.getReceiveNum());
		matMatter.setMatterName(policyDraw.getName());
		matMatter.setHandingDept(policyDraw.getImplemention());
		matMatter.setHandingDeptId(policyDraw.getCreateUserDept());
		matMatter.setMatterId(Integer.valueOf(cashAcceptDTO.getItemCode()));
		QueryWrapper<PolicyDrawProcess> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("matter_id", policyDraw.getId());
		queryWrapper.orderByAsc("create_time");
		List<PolicyDrawProcess> list = policyDrawProcessService.list(queryWrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			matMatter.setHandleStatus(list.get(0).getLink());
			matMatter.setDoStateName("办理中");
		}
		matMatter.setBankCode(cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("bankcode").toString());
		matMatter.setBankName(cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("bankname").toString());
		matMatter.setEnterpriseCode(cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("orgCode").toString());
		matMatter.setEnterpriseName(cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("orgName").toString());
		if (cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("remark") != null) {
			matMatter.setRemark(cashAcceptDTO.getFormData().get("ZhengCeDuiXian").get("remark").toString());
		}
		matMatter.setLinkMan(cashAcceptDTO.getInfo().get("linkMan").toString());
		matMatter.setLinkEmail(cashAcceptDTO.getInfo().get("linkManEmail").toString());
		matMatter.setLinkPhone(cashAcceptDTO.getInfo().get("contactPhone").toString());
		matMatter.setAppliedCashAmount(BigDecimal.valueOf(0));
		StringBuilder stringBuilder = new StringBuilder();
		if (CollectionUtils.isNotEmpty(cashAcceptDTO.getMetail())) {
			cashAcceptDTO.getMetail().forEach(item -> {
				stringBuilder.append(item.get("FILE_PATH") + ",");
			});
			stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
		}
		matMatter.setMetail(stringBuilder.toString());
		return save(matMatter);
	}

	public Boolean ehbCashAccept(EhbCashAcceptDTO cashAcceptDTO) {
		PolicyDraw policyDraw = policyDrawService.getById(Long.valueOf(cashAcceptDTO.getItemCode()));
		MatMatter matMatter = new MatMatter();
		matMatter.setHandleNum(cashAcceptDTO.getReceiveNum());
		matMatter.setMatterName(policyDraw.getName());
		matMatter.setHandingDept(policyDraw.getImplemention());
		matMatter.setHandingDeptId(policyDraw.getCreateUserDept());
		matMatter.setMatterId(Integer.valueOf(cashAcceptDTO.getItemCode()));
		QueryWrapper<PolicyDrawProcess> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("matter_id", policyDraw.getId());
		queryWrapper.orderByAsc("create_time");
		List<PolicyDrawProcess> list = policyDrawProcessService.list(queryWrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			matMatter.setHandleStatus(list.get(0).getLink());
			matMatter.setDoStateName("办理中");
		}
		Map<String, Object> formData = cashAcceptDTO.getFormData();
		matMatter.setBankCode(formData.get("bankcode").toString());
		matMatter.setBankName(formData.get("bankname").toString());
		matMatter.setEnterpriseCode(formData.get("orgCode").toString());
		matMatter.setEnterpriseName(formData.get("orgName").toString());
		if (formData.get("remark") != null) {
			matMatter.setRemark(formData.get("remark").toString());
		}
		matMatter.setLinkMan(cashAcceptDTO.getInfo().get("linkMan").toString());
		matMatter.setLinkEmail(cashAcceptDTO.getInfo().get("linkManEmail").toString());
		matMatter.setLinkPhone(cashAcceptDTO.getInfo().get("contactPhone").toString());
		matMatter.setAppliedCashAmount(BigDecimal.valueOf(0));
		StringBuilder stringBuilder = new StringBuilder();
		if (CollectionUtils.isNotEmpty(cashAcceptDTO.getMetail())) {
			cashAcceptDTO.getMetail().forEach(item -> {
				stringBuilder.append(item.get("FILE_PATH") + ",");
			});
			stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
		}
		matMatter.setMetail(stringBuilder.toString());
		return save(matMatter);
	}
}
